package com.user.servlet;

import com.user.entity.Users;
import com.user.service.IUserService;
import com.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "UserLoginServlet", value = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Users users = new Users(username, password);
        IUserService userService = new UserServiceImpl();
        boolean result = userService.userLogin(users);

        if (result == false) {
            HttpSession session = request.getSession();
            request.setAttribute("msg", "登录失败！检查用户名或密码!");
            session.setAttribute("username", null);
            request.getRequestDispatcher("User/userLogin.jsp").forward(request, response);
        } else {
            HttpSession session = request.getSession();
            request.setAttribute("msg", "");

            session.setAttribute("username", username);
            request.getRequestDispatcher("/BookListServlet").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
